/**
 * 这个端口生成遵循的模式是，去往同一reducer的流量都用同一个目的端口，源端口随机。
 * 参考资料是文章"coda"中观测到的spark这种应用场景下的端口设置情况。
 *
 * r_port是一个对象，存储了对应reducer的port号
 */

function getPattern(flowNum, hosts, r_ports) {
	var mNum, rNum;
	var result = [];

	do {
		mNum = Math.ceil(Math.random() * flowNum);
		rNum = flowNum / mNum;

	}while(Math.floor(rNum) !== rNum);

	var mappers = [];
	var reducers = [];


	//产生mapper的节点号
	for(var i = 0; i < mNum; i++){
		var mapper;
		
		do {
			mapper = Math.floor(Math.random() * hosts);

		}while(mappers.indexOf(mapper) !== -1);
		
		mappers.push(mapper);
	}

	//产生reducer的节点号以及端口号
	for(var i = 0; i < rNum; i++) {
		var reducer;

		do{
			reducer = Math.floor(Math.random() * hosts);
		}while(reducers.indexOf(reducer) !== -1);

		if(!(reducer in r_ports)) {
			var port = Math.floor(Math.random() * 100);
			r_ports[reducer] = port;
		}
		reducers.push(reducer);
	}

	//生成流的源端口号
	for(var i = 0; i < mNum; i++) {
		var s = mappers[i];
		for(var j = 0; j < rNum; j++) {
			var d = reducers[j];
			var port = r_ports[d];

			var traffic = "" + s + "-" + d + "-" + port;
			result.push(traffic); 
		}
	}

	return result;
}

module.exports = getPattern;

//test
/*
(function() {
	var flowNum = 4;
	hosts = 20; 
	r_ports = {};
	var result = getPattern(flowNum, hosts, r_ports);
	console.log(result);
})();
*/


